﻿using DotNet5.Mvc.FreeSqlBuilder;
using DotNet5.Mvc.Models;
using DotNet5.Mvc.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using DotNet5.Mvc.Common;
using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace DotNet5.Mvc.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IUsersService usersService;

        public HomeController(ILogger<HomeController> logger, IUsersService usersService)
        {
            _logger = logger;
            this.usersService = usersService;
        }

        public IActionResult Index()
        {
            try
            {
                //IList<USERS> uList = usersService.GetUsers().ToList();
                //_logger.LogInformation(JsonConvert.SerializeObject(uList));
                /* 
                IFreeSql fsql = FreeSqlFactory.CreateFreeSql();
                添加 
                var repo = fsql.GetRepository<Users>();
                var user = new Users { Name = $"张三_{ new Random().Next(1,100) }", Age = new Random().Next(10, 70), BirthDate = DateTime.Now };
                var addInfo = repo.Insert(user);
                _logger.LogInformation($"添加的用户信息：{ JsonHelper.ObjectToJSON(addInfo) }\n");
                */

                /* 查询
                var uList = fsql.Select<Users>().OrderByDescending<int>(c => c.Id) .ToList();
                //usersService.DeleteById(new[] { "13", "14" });

                IList<Users> uList = usersService.GetModelsAll().ToList();
                */

                PageObject<Users> po = usersService.GetModelsByPage<DateTime>(1, 15, false, c => c.BirthDate, c => c.Name != "");
                string jsonData = JsonHelper.ObjectToJSON(po);
                _logger.LogInformation($"查询的用信息：{ jsonData }");
                ViewData.Add("JsonData", jsonData);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
            }
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
